<template>
  <div class="app-container">
    <!-- <MySearchForm :searchForm="searchForm" /> -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="活动名称" prop="name">
        <el-input
          v-model="queryParams.name"
          maxlength="16"
          clearable
          style="width: 240px"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="城市标签" prop="cityName">
        <el-select
          v-model="queryParams.cityName"
          @change="handleQuery"
          fit-input-width
          placeholder="请选择"
        >
          <el-option
            v-for="item in cityNameOptions"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="&nbsp;">
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>

    <div v-for="item in positionOptions" :key="item.position">
      <div class="title">
        <span>{{ item.title }}投放</span>
        <el-button
          v-hasPermi="['advert:mini:add']"
          type="primary"
          icon="Plus"
          @click="handleAdd(item)"
          v-show="item.position !== 3 ? getDataList(item.position).count < item.length : true"
          >添加</el-button
        >
      </div>

      <el-table
        v-loading="loading"
        row-key="id"
        :data="item.position !== 3 ? getDataList(item.position).banners : popupList"
      >
        <el-table-column type="index" label="编号" width="50" align="center" />
        <el-table-column label="轮播图" align="center" prop="url" min-width="120">
          <template #default="{ row }">
            <el-image
              :src="row.img"
              preview-teleported
              hide-on-click-modal
              style="height: 100px"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[row.img]"
              :initial-index="0"
              fit="cover"
              class="form-img"
            />
          </template>
        </el-table-column>
        <el-table-column label="城市标签" align="center" prop="cityName" />
        <el-table-column
          label="活动名称"
          align="center"
          prop="name"
          min-width="120"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="备注"
          align="center"
          prop="remark"
          min-width="90"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="操作" align="center" min-width="140">
          <template #default="{ row }">
            <el-button
              v-if="item.position === 3"
              v-hasPermi="['advert:mini:details']"
              link
              type="primary"
              @click="handleEdit(row, item, '详情')"
              >详情</el-button
            >
            <el-button
              v-if="item.position !== 3"
              v-hasPermi="['advert:mini:edit']"
              link
              type="primary"
              @click="handleEdit(row, item)"
              >编辑</el-button
            >
            <el-button
              v-hasPermi="['advert:mini:delete']"
              link
              type="primary"
              @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
        <el-table-column align="center" width="60">
          <template #default="scope">
            <div class="operationBox">
              <el-button
                v-show="
                  scope.$index !== 0 ||
                  (scope.$index === 0 && queryParams.pageNum !== 1 && scope.row.position === 3)
                "
                text
                size="large"
                @click="handleoOperationSort(1, scope.row)"
                :icon="ArrowUpBold"
              />
              <el-button
                v-if="
                  scope.row.position !== 3
                    ? getDataList(item.position).banners.length - 1 !== scope.$index
                    : getShow(scope.$index)
                "
                text
                size="large"
                @click="handleoOperationSort(2, scope.row)"
                :icon="ArrowDownBold"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-bottom: 30px">
        <pagination
          v-show="total > 0 && item.position === 3"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="refresh"
          :pageSizes="[5, 10]"
        />
      </div>
    </div>

    <addDialog ref="addRef" :title="title" @refresh="refresh" />
  </div>
</template>

<script setup>
import { ArrowUpBold, ArrowDownBold } from '@element-plus/icons-vue'
import {
  getMiniBannersApi,
  deleteBannerApi,
  postBannerSortApi,
  getPopupListApi
} from '@/api/advert'
import addDialog from './cpts/addDialog.vue'
import { listDataApi } from '@/api/system/dict/data'
import useGlobalStore from '@/store/modules/global'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => {
  queryParams.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
  return globalStore.myCityList
})

const queryRef = ref(null)
const loading = ref(false)

const positionOptions = ref([])
const total = ref(0)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 5
})

const dataList = ref([])
const popupList = ref([])

const addRef = ref(null)
const title = ref('')

function refresh() {
  getList()
  getPopupList()
}

function getShow(index) {
  const length = popupList.value.length - 1
  if (length <= 1) {
    console.log('1', 1)
    return false
  } else {
    if (index < length) {
      console.log('2', 2)
      return true
    } else if (
      length === index &&
      (queryParams.pageNum - 1) * queryParams.pageSize + index + 1 < total.value
    ) {
      console.log('3', 3)
      return true
    } else {
      console.log('4', 4)
      return false
    }
  }
}

onMounted(() => {
  console.log('小程序广告')
  getList()
  getPopupList()
  getListData()
})

// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
  getPopupList()
}

// 重置
function resetQuery() {
  queryRef.value.resetFields()
  handleQuery()
}

// 获取列表
async function getList() {
  loading.value = true
  try {
    const res = await getMiniBannersApi(queryParams)
    dataList.value = res?.data || {}
    loading.value = false
  } catch {
    loading.value = false
  }
}
/**操作列表排序 */
function handleoOperationSort(direction, row) {
  console.log('row', row)
  postBannerSortApi({
    miniBannerId: row.id,
    direction,
    position: row.position
  }).then((res) => {
    getList()
    getPopupList()
  })
}
// 获取对应广告表格数据
function getDataList(position) {
  if (!dataList.value.length) return { banners: [], count: 0 }
  if (position !== 3) {
    return (
      dataList.value.find((i) => {
        return i.position === position
      }) || { banners: [], count: 0 }
    )
  }
}

// 获取弹窗列表
function getPopupList() {
  getPopupListApi({ ...queryParams, position: 3 }).then((res) => {
    popupList.value = res?.rows || []
    total.value = res?.total || 0
  })
}

// 添加
function handleAdd(row) {
  title.value = row.title
  row.cityName = queryParams.cityName
  addRef.value.init(row, '新增')
}
// 编辑
function handleEdit(row, item, type) {
  title.value = item.title
  row.cityName = queryParams.cityName
  if (type) {
    addRef.value.init(row, type, item.desc)
  } else {
    addRef.value.init(row, '设置', item.desc)
  }
}
// 删除
function handleDelete(row) {
  ElMessageBox.confirm('确认要删除' + '"' + row.name + '"' + '吗?', '系统提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: false
  })
    .then(() => {
      deleteBannerApi(row.id).then(() => {
        getList()
        getPopupList()
        ElMessage.success('删除成功')
      })
    })
    .catch(() => {})
}

/** 获取banner类型 */
const getListData = () => {
  listDataApi({ dictType: 'mini_ad_position' }).then((res) => {
    positionOptions.value = res?.rows.map((i) => {
      const remark = i.remark.split(';')
      return {
        title: i.dictLabel,
        position: i.dictValue - 0,
        length: remark[1] - 0,
        desc: remark[0]
      }
    })
    console.log(' positionOptions.value', positionOptions.value)
  })
}
</script>

<style lang="scss" scoped>
.form-img {
  min-width: 100px;
  height: 100px;
  margin-left: 8px;
  border-radius: 8px;
  cursor: pointer;
}
.title {
  font-size: 16px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}
.operationBox {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  ::v-deep .el-button {
    margin-left: 0px;
  }
}
</style>
